package com.example.onlinemusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.onlinemusic.common.R;
import com.example.onlinemusic.constant.Constants;
import com.example.onlinemusic.mapper.PayItemMapper;
import com.example.onlinemusic.mapper.PayMapper;
import com.example.onlinemusic.mapper.SongMapper;
import com.example.onlinemusic.model.domain.Pay;
import com.example.onlinemusic.model.domain.PayItem;
import com.example.onlinemusic.model.domain.Song;
import com.example.onlinemusic.model.request.SongRequest;
import com.example.onlinemusic.service.SongService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 歌曲管理接口实现类
 */
@Service
public class SongServiceImpl extends ServiceImpl<SongMapper, Song> implements SongService {
    @Autowired
    SongMapper songMapper;

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private PayItemMapper payItemMapper;

    @Override
    public R selectSongsBySingerId(int singerId) {
        // 根据歌手ID查询歌曲 select * from song where singer_id = 1
        // 定义查询条件
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("singer_id", singerId);
        // 调用mybatis提供的查询方法
        return R.success("查询成功", songMapper.selectList(queryWrapper));
    }

    @Override
    public R updateSong(SongRequest songRequest) {
        // 先去获取得到服务端的歌曲信息，判断歌曲存在后再进行属性赋值
        Song song = songMapper.selectById(songRequest.getId());
        if (song != null) {
            // BeanUtils.copyProperties(songRequest,song);
            song.setName(songRequest.getName());
            song.setIntroduction(songRequest.getIntroduction());
            song.setLyric(songRequest.getLyric());
            int i = songMapper.updateById(song);
            if (i > 0) {
                return R.success("更新成功");
            } else {
                return R.error("更新失败");
            }
        } else {
            return R.error("数据不存在");
        }
    }

    @Override
    public R deleteSong(int id) {
        if (songMapper.deleteById(id) > 0) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    @Override
    public R addSong(SongRequest songRequest, MultipartFile mpfile) {
        Song song = new Song();
        BeanUtils.copyProperties(songRequest, song);
        // 将二进制流文件转换成普通文件并保存
        String fileName = System.currentTimeMillis() + "-" + mpfile.getOriginalFilename();
        // 得到项目根路径
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            if (!file1.mkdir()) {
                return R.fatal("创建文件失败");
            }
        }
        // 在相应目录下创建文件
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeUrlPath = "/song/" + fileName;
        try {
            mpfile.transferTo(dest);
            System.out.println("文件存储路径：" + dest.getAbsolutePath());
        } catch (IOException e) {
            return R.fatal("上传失败" + e.getMessage());
        }
        // 设置操作的创建时间和更新时间为系统当前时间
        song.setCreateTime(new Date());
        song.setUpdateTime(new Date());
        // 设置歌曲的本地存储相对路径
        song.setUrl(storeUrlPath);
        // 设置歌曲图片地址
        song.setPic("https://java-pp.oss-cn-hangzhou.aliyuncs.com/img/songPic/1689093435201-tubiao.jpg");
        // 插入到数据库
        int i = songMapper.insert(song);
        if (i > 0) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }
    }

    @Override
    public R updateSongPic(MultipartFile mpfile, int id) {
        // 将图片文件保存到服务端
        String fileName = System.currentTimeMillis() + "-" + mpfile.getOriginalFilename();
        // 得到项目根路径
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img/songPic";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            if (!file1.mkdir()) {
                return R.fatal("创建文件失败");
            }
        }
        // 在相应目录下创建文件
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeUrlPath = "/img/songPic/" + fileName;
        try {
            mpfile.transferTo(dest);
            System.out.println("图片存储路径：" + dest.getAbsolutePath());
        } catch (IOException e) {
            return R.fatal("上传失败" + e.getMessage());
        }
        // 更新歌曲中图片的地址
        Song song = songMapper.selectById(id);
        song.setPic(storeUrlPath);
        song.setUpdateTime(new Date());
        int i = songMapper.updateById(song);
        if (i > 0) {
            return R.success("更新图片成功");
        } else {
            return R.error("更新图片失败");
        }
    }

    @Override
    public R songOfSingerName(String name) {
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",name);
        return R.success("查询成功",songMapper.selectList(queryWrapper));
    }

    @Override
    public R songDetail(int id) {
        return R.success("查询成功",songMapper.selectById(id));
    }

    @Override
    public R getSongDetail(int id) {
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        return R.success(null,songMapper.selectList(queryWrapper));
    }

    @Override
    public R allSong() {
        return R.success("查询成功",songMapper.selectList(null));
    }


    @Override
    public R isPay(Integer songId, Integer userId) {
        String msg = "查询歌曲支付状态时发生错误";
        try {
            QueryWrapper<PayItem> itemqw = new QueryWrapper<>();
            itemqw.eq("user_id", userId).eq("song_id", songId);
            List<PayItem> payItems = payItemMapper.selectList(itemqw);
            if (payItems == null) {
                return R.error(msg);
            }
            //歌曲未购买
            if (payItems.isEmpty()) {
                return R.warning("该歌曲还未支付");
            }

            //不等于0时，判断支付清单的状态
            QueryWrapper<Pay> payqw = new QueryWrapper<>();
            payqw.eq("trade_no", payItems.get(0).getTradeNo());
            List<Pay> pays = payMapper.selectList(payqw);

            if (pays == null || pays.size() < 1) {
                return R.error(msg);
            }

            if (pays.get(0).getPayStatus().equals(Constants.PAY_STATUS_1)) {
                return R.success("", true);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.error(msg);
        }
        return R.fatal(msg);
    }

}
